<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: jz
 * Date: 2016/8/22
 * Time: 17:03
 */

class Node extends MY_Controller{
    
    
    public function create_iso()
    {
        $sid = $this->input->get('sid');
        $tid = $this->input->get('tid');
        $uid = $this->session->userdata('uid');

        $this->load->model('node_model');

        $node = $this->node_model->find_opened_node(array('sid' => $sid, 'tid' => $tid));
        if ($node === false){
            $data = array(
                'uid' => $uid,
                'sid' => $sid,
                'tid' => $tid
            );
            $result = $this->post('http://127.0.0.1:9999/createiso', $data);
            if ($result === false){
                header("Content-type: text/html; charset=utf-8");
                echo "<h1>监控系统未开启</h1>";
                return;
            }
            $result = json_decode($result, true);

            if ($result['code'] != '0'){
                echo $result['error'];
                return;
            }
            $ip_port = mb_split(':', $result['node']);
            $node = array(
                'uid' => $uid,
                'sid' => $sid,
                'ip' => $ip_port[0],
                'port' => $ip_port[1],
                'tid' => $tid,
                'usetid' => '1'
            );
            $this->node_model->insert($node);
        }else {
            $node = $node[0];
            if ($this->node_is_exist($node['port']) === false){
                $this->node_model->delete($node['port']);
                return $this->create_iso();
            }
        }

        $this->load->model('address_model');
        $this->load->model('template_model');
        $result = $this->address_model->get_by_id($sid);
        if ($result === false){
            $node['name'] = '';
            $node['target_ip'] = '';
            $node['target_port'] = '';
        }else{
            $node['name'] = $result[0]['name'];
            $node['target_ip'] = $result[0]['ip'];
            $node['target_port'] = $result[0]['port'];
        }
        $result = $this->template_model->get_by_id($tid);
        if ($result === false){
            $node['template'] = array();
        }else{
            $node['template'] = $result[0];
            $node['template']['content'] = json_decode($node['template']['content'], true);
        }
        $node['sid'] = $sid;
        $this->load->view('monitor.html', $node);
    }
    
    
    
    public function create_raw()
    {
        $sid = $this->input->get('sid');
        $uid = $this->session->userdata('uid');

        $this->load->model('node_model');
            
        $node = $this->node_model->find_opened_node(array('sid' => $sid));
        if ($node === false){
            $data = array(
                'uid' => $uid,
                'sid' => $sid
            );
            $result = $this->post('http://127.0.0.1:9999/createraw', $data);
            if ($result === false){
                header("Content-type: text/html; charset=utf-8");
                echo "<h1>监控系统未开启</h1>";
                return;
                return;
            }
            $result = json_decode($result, true);

            if ($result['code'] != '0'){
                echo $result['error'];
                return;
            }
            $ip_port = mb_split(':', $result['node']);
            $node = array(
                'uid' => $uid,
                'sid' => $sid,
                'ip' => $ip_port[0],
                'port' => $ip_port[1],
                'usetid' => '0'
            );
            $this->node_model->insert($node);
        }else {
            $node = $node[0];
            if ($this->node_is_exist($node['port']) === false){
                $this->node_model->delete($node['port']);
                return $this->create_raw();
            }
        }
        
        $this->load->model('address_model');
        $result = $this->address_model->get_by_id($sid);
        if ($result === false){
            $node['name'] = '';
            $node['target_ip'] = '';
            $node['target_port'] = '';
        }else{
            $node['name'] = $result[0]['name'];
            $node['target_ip'] = $result[0]['ip'];
            $node['target_port'] = $result[0]['port'];
        }
        $node['sid'] = $sid;
        $this->load->view('monitor.html', $node);
    }
    
    private function post($url, $data)
    {
        $postdata = http_build_query($data, '', '&');
        $opts = array(
            'http' =>
                array(
                    'method'  => 'POST',

                    'header'  => 'Content-type: application/x-www-form-urlencoded',

                    'content' => $postdata
                )
        );
        $context = stream_context_create($opts);
        $result = @file_get_contents($url, false, $context);
        return $result;
    }
    
    public function delete_node()
    {
        $tid = $this->input->post('tid');
        $sid = $this->input->post('sid');

        $this->load->model('node_model');

        if ($tid === ''){
            $node = $this->node_model->find_opened_node(array('sid' => $sid));
        }else {
            $node = $this->node_model->find_opened_node(array('tid' => $tid, 'sid' => $sid));
        }
        if ($node !== false){
            $data = array(
                'nodeid' => $node[0]['port']
            );
            $result = $this->post('http://127.0.0.1:9999/deletenode', $data);
            if ($result !== false){
                $result = json_decode($result, true);
                if ($result['code'] != '0'){
                    $result['code'] = '-1';
                    $result['msg'] = '删除失败';
                    goto err;
                }
            }
            if ($this->node_model->delete($node[0]['port']) != true){
                $result['code'] = '-1';
                $result['msg'] = '删除失败';
                goto err;
            } 
        }
        unset($result);
        $result['code'] = '0';
        $result['msg'] = 'ok';
        $output = json_encode($result);
        echo $output;
        return;
    err:
        $output = json_encode($result);
        echo $output;

    }
    
    public function node_is_exist($port = '')
    {
        $data = array(
          'nodeid' => $port  
        );

        $result = $this->post('http://127.0.0.1:9999/node/exist', $data);
        if ($result === false){
            return false;
        }
        $result = json_decode($result, true);
        if ($result['code'] != '0'){
            return false;
        }
    }
}